package com.example.foo.admin.web.account;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.web.bind.annotation.GetMapping;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtils;
import com.example.core.PageResult;
import com.example.core.Pageable;
import com.example.foo.account.model.Account;
import com.example.foo.account.query.AccountQuery;
import com.example.foo.account.service.AccountService;
import com.example.foo.ftt.model.FttUser;
import com.example.foo.ftt.service.FttUserService;

@org.springframework.web.bind.annotation.RestController
public class AccountAction {

	private final AccountService accountService;
	private final FttUserService fttUserService;

	public AccountAction(AccountService accountService,
			FttUserService fttUserService) {
		this.accountService = accountService;
		this.fttUserService = fttUserService;
	}

	@GetMapping("/api/accounts")
	public AjaxResult index(AccountQuery accountQuery, Pageable pageable) {
		PageResult<Account> pageResult = accountService.findAccounts(accountQuery, pageable);

		List<Long> userIds = pageResult.getRows().stream()
				.map(Account::getUserId)
				.collect(Collectors.toList());
		Map<Long, FttUser> userIdFttUserMap = fttUserService.findFttUsersByUserIdsAsMap(userIds);

		List<AccountVO> accountVOs = pageResult.getRows()
				.stream()
				.map(account -> new AccountVO(account, userIdFttUserMap.get(account.getUserId())))
				.collect(Collectors.toList());
		return AjaxResult.successData(new PageResult<>(accountVOs, pageResult.getTotal()));
	}

	@GetMapping("/api/accounts/export")
	public AjaxResult export(AccountQuery accountQuery) {
		Pageable pageable = new Pageable(1, 65535);
		PageResult<Account> pageResult = accountService.findAccounts(accountQuery, pageable);

		List<Long> userIds = pageResult.getRows().stream()
				.map(Account::getUserId)
				.collect(Collectors.toList());
		Map<Long, FttUser> userIdFttUserMap = fttUserService.findFttUsersByUserIdsAsMap(userIds);

		List<AccountVO> accountVOs = pageResult.getRows()
				.stream()
				.map(account -> new AccountVO(account, userIdFttUserMap.get(account.getUserId())))
				.collect(Collectors.toList());

		Map<String, String> fields = new LinkedHashMap<>();
		fields.put("ID", "id");
		fields.put("科目", "acctc");
		fields.put("科目T", "acctcText");
		fields.put("符号", "drcrbal");
		fields.put("符号T", "drcrbalText");
		fields.put("总计", "total");
		fields.put("userId", "userId");
		fields.put("角色", "roleLevel");
		fields.put("角色T", "roleLevelText");
		fields.put("网体级别", "fttLevel");
		fields.put("网体级别T", "fttLevelText");
		fields.put("手机号", "cellphone");
		fields.put("姓名", "idname");
		return new ExcelUtils<>(AccountVO.class).export(fields, accountVOs);
	}

}
